// 
// 
// 

#include "Input.h"
#include "LedFxUtilities.h"
int hueEncode = 0,satEcode = 0;
uint8_t hue,saturation,value;

void initInputs() {
  pinMode(B_PIN, OUTPUT);
  pinMode(BUTTON_1_PIN, INPUT);
  pinMode(BUTTON_2_PIN, INPUT);

  pinMode(G_PIN, OUTPUT);
  pinMode(R_PIN, OUTPUT);
  pinMode(H_ENCODER_1_PIN, INPUT_PULLUP);
  pinMode(H_ENCODER_2_PIN, INPUT_PULLUP);
  pinMode(S_ENCODER_1_PIN, INPUT_PULLUP);
  pinMode(S_ENCODER_2_PIN, INPUT_PULLUP);
  hue=0;
  saturation = 255;
  value = 255;
  updateKnobs();
}
void updateKnobs() {
  RGB rgb =LEDFxUtilities::HSVtoRGB(hue,saturation,value);
  updateKnobs(rgb);
}
void updateKnobs(RGB rgb) {
  analogWrite(R_PIN, 255-rgb.r);
  analogWrite(G_PIN, 255-rgb.g);
  analogWrite(B_PIN, 255-rgb.b);
}

unsigned long modeChange = 0;
bool update(Mode & m) {
  uint8_t newHue = readEncoded(hue, H_ENCODER_1_PIN, H_ENCODER_2_PIN, hueEncode,1  );
  int newSat = readEncoded(saturation, S_ENCODER_1_PIN, S_ENCODER_2_PIN, satEcode,2 );
  bool retVal = false;
  if(digitalRead(BUTTON_1_PIN) == HIGH) {
    if(millis() - modeChange > 500) {
      modeChange = millis();
      m = (Mode)(((uint8_t)m + 1) % (Last+1));
      retVal = true;
    }
  }
/*  else if (digitalRead(BUTTON_2_PIN) == HIGH) {
    m = Solid;
    retVal = true;
  }*/
  if(newHue != hue) {
    hue = (newHue % 256);
    updateKnobs();
    retVal = true;
  }
  if(newSat != saturation) {
      saturation = min(max(newSat,0),255);
      updateKnobs();
      retVal = true;
  }
  return retVal;
}

int readEncoded(int value, int pin1, int pin2, int & prevEncoded, int delta) {
  int MSB = digitalRead(pin1); //MSB = most significant bit
  int LSB = digitalRead(pin2); //LSB = least significant bit

  int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
  int sum  = (prevEncoded << 2) | encoded; //adding it to the previous encoded value

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) value += delta;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) value -= delta;
  prevEncoded = encoded;
  return value;
}


